package auth

import (
	"github.com/dgrijalva/jwt-go"
	"log"
	"time"
)

var mySigningKey = []byte("my secret key")

type Claims struct {
	UserId   int
	UserName string
	jwt.StandardClaims
}

//IssueToken 生成令牌字符串
func IssueToken(id int, name string) string {
	//令牌周期设为一周
	expireAt := time.Now().Add(7 * 24 * time.Hour).Unix()
	issueAt := time.Now().Unix()
	claims := &Claims{
		UserId:   id, //令牌中增加用户ID和用户名
		UserName: name,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireAt,
			IssuedAt:  issueAt,
			Issuer:    "fm",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	log.Println(token)

	tokenString, err := token.SignedString(mySigningKey)
	if err != nil {
		log.Println("sign token error:", err.Error())
	}
	return tokenString
}

//ParseToken 验证令牌是否正确
func ParseToken(tokenString string) (int, string, error) {

	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte("my secret key"), nil
	})
	if err != nil {
		return 0, "", err
	}
	claims = token.Claims.(*Claims)
	userid := claims.UserId
	name := claims.UserName
	expiredAt := claims.ExpiresAt
	t := time.Unix(expiredAt, 0)
	date := t.Format("2006/01/02 15:04:05")
	log.Println("ParseToken:", "userid:", userid, "\tusername:", name, "\texpiredAt:", date)

	return userid, name, nil
}
